import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    book: {},
    cart: [],
  },
  mutations: {//修改state中变量值
    addGoods(state, bk) {
      let index = -1;
      for (let i = 0; i < state.cart.length; i++) {
        if (bk.id === state.cart[i].id) {
          index = i;
          break;
        }
      }
      if (index >= 0) {
        if(state.cart[index].number<bk.pnum){
          state.cart[index].number++;
          state.cart[index].lineTotal += bk.price;
        }else{

        }        
      }
      else {
        bk['number'] = 1;
        bk['lineTotal'] = bk.price;
        state.cart.push(bk);
      }
    },
    refresh(state, params) {//params={val:3,index:3}val是商品数量新的值，index购物车下标
      state.cart[params.index].lineTotal = state.cart[params.index].price * params.val;
      let bk = state.cart[params.index];
      state.cart.splice(params.index, 1, bk)//先删除，再插入，这样就会触发vue的渲染机制
    },
    delGoodsByIndex(state, index) {
      state.cart.splice(index, 1);
    }
  },
  actions: {
    addGoods(context, bk) {
      context.commit('addGoods', bk)
    },
    refresh(context, params) {
      context.commit('refresh', params)
    },
    delGoodsByIndex(context, index) {
      context.commit('delGoodsByIndex', index)
    }
  },
  modules: {
  },
  getters: {
    getGoodsCartNumber(state) {
      return function (id) {
        let index = -1;
        for (let i = 0; i < state.cart.length; i++) {
          if (id === state.cart[i].id) {
            index = i;
            break;
          }
        }
        if(index>=0){
          return state.cart[index].number;
        }else{
          return 0;
        }
        
      }
    },
    totalPrice(state) {
      let price_total = 0;
      for (let i = 0; i < state.cart.length; i++) {
        price_total +=
          state.cart[i].price * state.cart[i].number;
      }
      return price_total;
    },
    totalNumber(state) {
      let number_total = 0;
      for (let i = 0; i < state.cart.length; i++) {
        number_total += state.cart[i].number;
      }
      return number_total;
    },
  }
})
